package com.javaweb.secondhand_trading.service.Impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.javaweb.secondhand_trading.Dto.LoginDto;
import com.javaweb.secondhand_trading.Dto.RegisterDto;
import com.javaweb.secondhand_trading.common.exception.BusinessException;
import com.javaweb.secondhand_trading.entity.User;
import com.javaweb.secondhand_trading.mapper.UserMapper;
import com.javaweb.secondhand_trading.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URI;
import java.util.Base64;

import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

import java.nio.charset.StandardCharsets;

import java.util.HashMap;
import java.util.Map;

/**
 * 认证服务实现类
 * 处理用户注册和登录相关业务逻辑
 */
@Service // 标识为Spring服务组件
public class AuthServiceImpl implements AuthService {

    @Autowired // 自动注入用户数据访问接口
    private UserMapper userMapper;

    /**
     * 用户注册
     * @param registerDto 注册信息传输对象，包含用户名和密码
     * @throws BusinessException 如果用户名已存在
     *
     * 安全问题：当前直接存储明文密码，存在安全隐患！
     * 建议：应使用密码加密存储（如BCryptPasswordEncoder）
     */


    @Override
    public void register(RegisterDto registerDto) {
        // 检查用户名是否已存在
        if (userMapper.findByUsername(registerDto.getUsername()) != null) {
            throw new BusinessException("用户名已存在");
        }

        // 创建用户实体并保存
        User user = new User();
        user.setUsername(registerDto.getUsername());
        user.setPassword(registerDto.getPassword()); // ⚠️ 注意：生产环境请加密！
        userMapper.insert(user);

        // 获取用户 ID
        int userId = userMapper.findByUsername(user.getUsername()).getUserId();

        // 获取图片字节流并转 Base64

        String base64Image = registerDto.getImage();
        String imageData = "data:image/jpeg;base64," + base64Image;

        // 构造 JSON 请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("id", userId);
        requestBody.put("image", imageData);

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(requestBody);

            HttpClient client = HttpClient.newHttpClient();
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create("http://127.0.0.1:5000/api/python/register")) // 替换为实际地址
                    .header("Content-Type", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString(json, StandardCharsets.UTF_8))
                    .build();

            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

            if (response.statusCode() != 200) {
                throw new RuntimeException("Python 服务返回错误: " + response.body());
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("调用 Python 服务失败: " + e.getMessage());
        }
    }


    /**
     * 用户登录
     * @param loginDto 登录信息传输对象，包含用户名和密码
     * @return 登录成功的用户实体
     * @throws BusinessException 如果用户名或密码错误
     *
     * 安全问题：当前使用明文密码比对，存在安全隐患！
     * 建议：应使用加密后的密码进行比对
     */
    @Override
    public User login(LoginDto loginDto) {
        // 查询用户
        User user = userMapper.findByUsername(loginDto.getUsername());

        // 验证用户是否存在及密码是否正确
        if (user == null || !user.getPassword().equals(loginDto.getPassword())) {
            throw new BusinessException("用户名或密码错误");
        }

        return user; // 返回用户信息（注意：实际应用中可能需要返回Token而非完整用户对象）
    }

    @Override
    public User loginByFace(String base64Image) {
        try {
            // 构造请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("image", base64Image);

            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(requestBody);

            // 发起 POST 请求
            HttpClient client = HttpClient.newHttpClient();
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create("http://localhost:5000/api/python/login")) // 替换成你的 Python 接口
                    .header("Content-Type", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString(json))
                    .build();

            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

            if (response.statusCode() == 200) {
                JsonNode jsonResponse = objectMapper.readTree(response.body());

                int code = jsonResponse.get("code").asInt();
                if (code == 200 && jsonResponse.has("data")) {
                    int userId = jsonResponse.get("data").get("id").asInt();
                    User user = userMapper.findById(userId);
                    if (user != null) {
                        return user;
                    } else {
                        throw new BusinessException("用户不存在");
                    }
                } else {
                    String message = jsonResponse.has("message") ? jsonResponse.get("message").asText() : "识别失败";
                    throw new BusinessException("人脸识别失败: " + message);
                }
            } else {
                throw new BusinessException("识别服务异常，状态码: " + response.statusCode());
            }

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            throw new BusinessException("人脸登录异常: " + e.getMessage());
        }
    }

}
